<!-- @/components/ComponentPage.vue -->
<template>
  <div class="component-page">
    <h2>{{ title }}</h2>

    <!-- 组件网格 -->
    <a-row :gutter="[16, 16]" style="margin-bottom: 20px;">
      <a-col v-for="(comp, index) in currentPageComponents" :key="index" :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
        <div class="component-item">
          <!-- 异步组件渲染 -->
          <component :is="comp.component" />

          <!-- 查看代码按钮 -->
          <div class="component-code" @click="handleCopyCode(comp.name)">Get Code</div>
        </div>
      </a-col>
    </a-row>

    <!-- 分页器 -->
    <a-pagination v-model:current="currentPage" :total="totalComponents" :page-size="pageSize"
      @change="handlePageChange" show-less-items style="text-align: center;" />

    <!-- 统计信息（可选） -->
    <!-- <div style="text-align: center; margin-top: 10px; color: #999;">
      共 {{ totalComponents }} 个组件，每页 {{ pageSize }} 个
    </div> -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted, defineProps, defineEmits } from 'vue'
import { useRouter } from 'vue-router'
import { defineAsyncComponent } from 'vue'

// 👇 定义 props
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  componentGlob: {
    type: Object,
    required: true
  },
  pageSize: {
    type: Number,
    default: 8
  },
  // 是否自动从路径提取组件名（默认 true）
  autoExtractNames: {
    type: Boolean,
    default: true
  }
})

// 👇 定义事件（可选：用于通知父组件点击了哪个组件）
const emit = defineEmits(['code-click', 'page-change'])

const router = useRouter()
const currentPage = ref(1)

// 📦 提取所有组件路径和名称
const allComponentPaths = computed(() => {
  if (!props.autoExtractNames) return []

  return Object.keys(props.componentGlob).map(path => {
    const match = path.match(/([^/]+)\.vue$/)
    const name = match ? match[1] : path.split('/').pop().replace('.vue', '')
    return { path, name }
  })
})

// 🧮 总组件数量
const totalComponents = computed(() => allComponentPaths.value.length)

// 🔄 计算当前页组件（返回 { name, component } 对象）
const currentPageComponents = computed(() => {
  const start = (currentPage.value - 1) * props.pageSize
  const end = start + props.pageSize
  const pageItems = allComponentPaths.value.slice(start, end)

  return pageItems.map(item => {
    const component = defineAsyncComponent(() =>
      props.componentGlob[item.path]().then(mod => mod.default)
    )
    return {
      name: item.name,
      component
    }
  })
})

// 📄 点击“查看代码”或“复制”
const handleCopyCode = (componentName) => {
  emit('code-click', componentName) // 可选：供父组件监听
  router.push(`/preview/${componentName}`)
}

// 🔄 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  emit('page-change', page)
}

// 💡 初始化提示
onMounted(() => {
  console.log(`[ComponentPage] "${props.title}" 加载完成，共 ${totalComponents.value} 个组件`)
})
</script>

<style scoped>
@import '../assets/mainCard.css';

.component-page {
  padding: 20px;
}

.component-item {
  transition: box-shadow 0.2s ease;
  text-align: center;
  padding: 16px;
  /* border: 1px solid #eee; */
  border-radius: 8px;
  background: #212121;
}

.component-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>